import { onMounted, ref, watch, type Ref } from 'vue';

export default function useColWidth(
  containerRef: Ref<HTMLDivElement | null>,
  props: {
    data: Record<string, any>[] | null;
    columns: number;
    columnGap: number;
    picturePreReading: boolean;
  }
) {
  const colWidth = ref<number>(0);

  const containerLeft = ref<number>(0);

  watch(
    () => props.columns,
    newVal => {
      setTimeout(async () => {
        updateColWidth(containerRef, { ...props, columns: newVal });
      }, 100);
    }
  );

  onMounted(() => {
    updateColWidth(containerRef, props);
  });

  function updateColWidth(
    container: Ref<HTMLDivElement | null>,
    props: {
      columns: number;
      columnGap: number;
      picturePreReading: boolean;
    }
  ) {
    if (props.picturePreReading) {
      colWidth.value = 0;
    }

    const cssStyle = getComputedStyle(container.value as Element, null);
    const { paddingLeft, paddingRight } = cssStyle;

    containerLeft.value = parseFloat(paddingLeft);

    colWidth.value =
      (containerRef.value?.offsetWidth! -
        parseFloat(paddingLeft) -
        parseFloat(paddingRight) -
        (props.columns - 1) * props.columnGap) /
      props.columns;
  }

  return { colWidth, containerLeft };
}
